<?php

namespace Sharks\Core\Persistence\QueryBuilder;

use Sharks\Core\Persistence\Db;

/**
 * SQL Insert
 * <pre>
 *      Query::createInsert()->into('SysUser')->set('loginname', 'root')->get();
 *
 * </pre>
 */
class InsertQuery extends AbstractQuery {

    protected $insertQuery;
    protected $identifier;

    public function __construct($identifier) {
        $this->insertQuery = Db::connector($identifier)->createInsertQuery();
        $this->identifier = $identifier;
    }

    /**
     * 插入的数据表
     * @param $table
     * @return $this
     */
    public function into($table) {
        $this->insertQuery->insertInto($table);
        return $this;
    }

    /**
     * 设置数组
     * @param $column
     * @param $value
     * @return $this
     */
    public function set($column, $value) {
        $this->insertQuery->set($column, $this->insertQuery->bindValue($value));
        return $this;
    }

    /**
     * 设置数组参数
     * @param array $datas
     * @return $this
     */
    public function sets(array $datas) {
        foreach ($datas as $column => $value) {
            $this->set($column, $value);
        }
        return $this;
    }

    /**
     * 执行SQL,并获取SQL执行的返回值
     */
    public function get() {
        $stmt = $this->insertQuery->prepare();
        $stmt->execute();
        $this->checkError($stmt);

        return Db::connector($this->identifier)->lastInsertId();
    }

    /**
     * 返回执行的SQL
     * @return string
     */
    public function toSql() {
        return $this->insertQuery->getQuery();
    }
}